今天實作要做的是一個瀏覽網頁時常見的一種特效,就是當你閱讀一篇很長的文章時,滾動頁面到有圖片的段落時,圖片才會從側邊淡入進來,讓人產生一種這個網頁很有質感的錯覺,實作範例如下。
function debounce(func, wait = 20, immediate = true) {
var timeout;
return function () {
var context = this, args = arguments;
var later = function () {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
}
const slideInAt = (window.scrollY + window.innerHeight);
const imageBottom = sliderImage.offsetTop + sliderImage.height;
const isHalfShown = slideInAt > sliderImage.offsetTop + sliderImage.height / 2;
const isNotScrolledPast = window.scrollY < imageBottom;
if (isHalfShown && isNotScrolledPast) {
sliderImage.classList.add('active');
} else {
sliderImage.classList.remove('active');
}
function debounce(func, wait = 20, immediate = true)
參數帶入值代表預設,因此若要使用預設參數,只需debounce(func)
這樣呼叫即可。若要改變參數就正常給參數,如debounce(func,100)
。若只要給第三個參數就debounce(func,undefined,false)